package com.zeoy.keeplivetestdemo.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.zeoy.keeplivetestdemo.R;
import com.zeoy.keeplivetestdemo.aidl.KeepLiveAidlInterface;
import com.zeoy.keeplivetestdemo.utils.ServiceCheckUtils;

/**
 * Created by Administrator on 2018\3\21 0021.
 */

public class ForeGroundService extends Service {

    public static final int FLOG = 1000;
    private IBinder binder;
    private ServiceConnection connection;
    private Intent intent;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        binder = new KeepLiveAidlInterface.Stub() {
            @Override
            public String getServiceName() throws RemoteException {
                return "ForeGroundService";
            }
        };
        intent = new Intent(this, BackGroundService.class);
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e("zeoy", "【前台   -  断开连接后台  -  启动后台】");
                startService(intent);
                bindService(intent, connection, BIND_IMPORTANT);
            }
        };

        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("前台服务")
                .setContentText("正在运行中")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setWhen(System.currentTimeMillis())
                .build();


        //设置通知默认效果
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("zeoy", "【       前台重新启动】");
        if (!ServiceCheckUtils.isServiceWorked(this, "com.zeoy.keeplivetestdemo.service.BackGroundService")) {
            Log.e("zeoy", "【前台   -  启动  - 后台】");
            startService(intent);
        }
        bindService(intent, connection, BIND_IMPORTANT);
        return START_STICKY;
    }

    private String TAG = "ForeGroundService";

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        //重启自己
        Log.e("zeoy", "【       前台销毁】");
        /*Intent intent = new Intent(getApplicationContext(), ForeGroundService.class);
        startService(intent);*/
    }

}
